package com.edu.buservice.facade;

import cn.dev33.satoken.stp.StpUtil;
import com.edu.buservice.facade.constants.SessionKeyConstant;
import com.edu.buservice.facade.facade.TenantFacade;
import com.edu.buservice.facade.model.response.TenantDTO;
import com.edu.buservice.util.model.TenantContext;
import com.edu.buservice.util.model.TenantUtil;
import com.edu.buservice.util.model.UserInfoDTO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Objects;

/**
 * @program: KQAIA
 * @description: 租户上下文拦截器
 * @author: 无恙
 * @create: 2025-03-17 11:27
 **/

@Slf4j
public class TenantInterceptor implements HandlerInterceptor {

	@DubboReference(interfaceClass = TenantFacade.class)
	private TenantFacade tenantFacade;

	//拦截白名单
	private static final String[] WHITE_LIST = {
			"/buservice/user/login",
			"/buservice/user/register",
			"/buservice/user/queryTenant",
			"/buservice/user/addUser"
	};


	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		log.info("------------------------租户上下文拦截器---------------------------------");

		for (String s : WHITE_LIST) {
			if (request.getRequestURI().contains(s)){
				return true;
			}
		}

		if(!StpUtil.isLogin()){
			return true;
		}
		UserInfoDTO userInfoDTO = StpUtil.getSession().get(SessionKeyConstant.USER_INFO, new UserInfoDTO());

		if(Objects.isNull(userInfoDTO)){
			log.error("租户不存在,租户ID：{}", "没有找到会话信息");
			return false;
		}

		TenantDTO tenantById = tenantFacade.getTenantById(userInfoDTO.getTenantId());

		if (Objects.isNull(tenantById)){
			log.error("租户不存在,租户ID：{}", userInfoDTO.getTenantId());
			return false;
		}


		TenantContext tenantContext = new TenantContext();
		tenantContext.setTenantId(userInfoDTO.getTenantId());
		tenantContext.setTenantName(tenantById.getTenantName());
		tenantContext.setRole(userInfoDTO.getRole());
		tenantContext.setPermissions(userInfoDTO.getPermissions());
		tenantContext.setUserInfo(userInfoDTO);
		tenantContext.setUserId(userInfoDTO.getUserId());
		TenantUtil.init(tenantContext);
		log.info("租户上下文拦截器初始化成功:{}", tenantContext);

		return true;


	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

		log.info("------------------------租户上下文后置拦截器---------------------------------");
		if (StpUtil.isLogin()){
			TenantUtil.clear();
		}

	}
}
